#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2022/2/10 15:12
    Desc  :
--------------------------------------
"""
from user_agents import parse


def get_ip_address(request):
    """根据request获取请求ip"""
    if request.META.get('HTTP_X_FORWARDED_FOR'):
        ip = request.META.get("HTTP_X_FORWARDED_FOR")
    else:
        ip = request.META.get("REMOTE_ADDR")

    return ip


def get_browser_info(request):
    """根据request获取浏览器信息"""
    user_agent_str = request.environ.get("HTTP_USER_AGENT")
    if user_agent_str:
        user_agent = parse(user_agent_str)
        return dict(os = f'{user_agent.os.family} {user_agent.os.version_string}',
                    browser = f'{user_agent.browser.family} {user_agent.browser.version_string}',
                    device = f'{"PC" if user_agent.is_pc else user_agent.device.family} '
                             f'{user_agent.device.brand if user_agent.device.brand else ""}'.strip()
                    )
    else:
        return dict()


def get_location_address_by_ip(ip: str):
    """根据ip获取地理位置"""

    import requests
    from bs4 import BeautifulSoup
    import re

    url = "https://www.ip138.com/iplookup.asp?ip={}&action=2".format(ip)

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36'
    }

    # 获取响应
    response = requests.get(url = url, headers = headers)

    response.encoding = "gb2312"

    html = response.text
    data = dict()
    address = ''
    for match in re.finditer('"(prov|city|ct)":"(.*?)"', html):
        n_str = '{' + match.group() + '}'
        prov_dict = dict(eval(n_str))
        key = list(prov_dict.keys())[0]
        data[key] = prov_dict.get(key)

    # return data
    address += f'{data.get("ct")} ' \
               f'{data.get("prov") if data.get("prov") != "" and data.get("prov") else ""} ' \
               f'{data.get("city") if data.get("city") != "" and data.get("city") else ""} '.strip()
    return address


if __name__ == '__main__':
    print(get_location_address_by_ip('183.94.167.87'))
    print(get_location_address_by_ip('192.168.80.236'))
